//
//  TranslationPictureController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/5/6.
//

import UIKit
import AVFoundation
import SnapKit
import Reusable

class TranslationPictureController: BaseViewController {
    
    /// 切换语言
    private lazy var rightBarItem: TranslationPictureBarItem = {
        TranslationPictureBarItem.loadFromNib()
    }()
    
    
    private var language: LanguageTpye = .zh {
        didSet {
            rightBarItem.titleLabel.text = language == .zh ? "中文".localized(.login): "俄语".localized(.login)
        }
    }
    
    var titleLabel: UILabel!
    
    lazy var barView: TranslationPictureBarView = {
        let barView = TranslationPictureBarView.loadFromNib()
        barView.cameraButton.addTarget(self, action: #selector(cameraAction), for: .touchUpInside)
        barView.photoButton.addTarget(self, action: #selector(photoAction), for: .touchUpInside)
        view.addSubview(barView)
        return barView
    }()
    
    private lazy var resultView: TranslationPictureResultView = {
        let resultView = TranslationPictureResultView.loadFromNib()
        resultView.resetButton.addTarget(self, action: #selector(resetAction), for: .touchUpInside)
        resultView.isHidden = true
        view.addSubview(resultView)
        return resultView
    }()
    
    
    // 初始化捕获会话
    var captureSession: AVCaptureSession!
    var previewLayer: AVCaptureVideoPreviewLayer!
    var photoOutput: AVCapturePhotoOutput!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNav()
        setupUI()
        language = LanguageManager.isCountryCN ? .zh: .ru
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if captureSession.isRunning {
            captureSession.stopRunning()
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // 确保预览层覆盖整个视图的范围
        previewLayer.frame = CGRect(x: 0, y: 0, width: xScreenW, height: xScreenH)
    }
    
    @objc func toggleLanguageAction() {
        
        let alerController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        
        let cancelAction = UIAlertAction(title: "取消".localized(), style: .cancel)
        alerController.addAction(cancelAction)
        
        let zhAction = UIAlertAction(title: "\("中文".localized(.login)) -> \("俄语".localized(.login))", style: .default) { action in
            xLog("中文")
            self.language = .zh
        }
        alerController.addAction(zhAction)
        
        let ruAction = UIAlertAction(title: "\("俄语".localized(.login)) -> \("中文".localized(.login))", style: .default) { action in
            xLog("俄语")
            self.language = .ru
        }
        alerController.addAction(ruAction)
        present(alerController)
        
    }
}

// MARK: - private
private extension TranslationPictureController {
    
    func setupNav() {
        vhl_navBarBackgroundAlpha = 0
        rightBarItem.sg.addTapGesture(self, #selector(toggleLanguageAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBarItem)
    }
    
    func setupUI() {
        setupAVCapture()
        barView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-xIphoneBottomSafeHeight)
            make.height.equalTo(75)
        }
        
        resultView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
    }
    
    func setupAVCapture() {
        
        captureSession = AVCaptureSession()
        
        // 获取后置摄像头
        guard let frontCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {
            return
        }
        
        do {
            // 创建输入对象
            let input = try AVCaptureDeviceInput(device: frontCamera)
            
            // 将输入添加到会话中
            if captureSession.canAddInput(input) {
                captureSession.addInput(input)
            }
            
            photoOutput = AVCapturePhotoOutput()
            if captureSession.canAddOutput(photoOutput) {
                captureSession.addOutput(photoOutput)
            } else {
                print("Error: Could not add photo output to the session.")
            }
            
            // 创建预览层以显示相机内容
            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            // 设置为全屏显示
            previewLayer.frame = CGRect(x: 0, y: xIphoneNavStatusBarHeight, width: xScreenW, height: xScreenH)
            previewLayer.videoGravity = .resizeAspectFill
            
            view.layer.addSublayer(previewLayer)
            
            DispatchQueue.global().async {
                /// 异步线程
                // 开始会话
                self.captureSession.startRunning()
            }
            
        } catch {
            print("Error setting up camera input: \(error)")
        }
    }
    
    /// 创建切换语言按钮
    func createStyledPullDownButton() -> UIButton {
        var config = UIButton.Configuration.filled()
        config.title = "中文".localized(.login)
        config.image = UIImage(named: "ic_tran_arrow_down")
        config.imagePlacement = .trailing
        config.imagePadding = 4
        config.cornerStyle = .fixed
        config.baseBackgroundColor = .black.setAlpha(0.4)
        
        let button = UIButton(configuration: config, primaryAction: nil)
        button.showsMenuAsPrimaryAction = true
        // 设置字体大小
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        
        // 创建菜单
        let menuItems = [
            UIAction(title: "中文".localized(.login)) { _ in
                xLog("中文")
                self.language = .zh
            },
            UIAction(title: "俄语".localized(.login)) { _ in
                xLog("俄语")
                self.language = .ru
            }
        ]
        
        button.menu = UIMenu(children: menuItems)
        return button
    }
}

// MARK: - Action
extension TranslationPictureController {
    
    @objc func cameraAction() {
        let settings = AVCapturePhotoSettings()
        photoOutput.capturePhoto(with: settings, delegate: self)
        
        //        resultView.addItem(TranslationPictureResultItem(type: 0, image: "lufei".toImage))
        //        resultView.addItem(TranslationPictureResultItem(type: 1, image: "lufei".toImage))
        //        resultView.isHidden = false
        //        toggleButton.isHidden = true
        
    }
    
    @objc func photoAction() {
        // 打开相册
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = false // 允许编辑图片（可选）
            present(imagePicker, animated: true, completion: nil)
        } else {
            print("没有可用的相册源")
        }
    }
    
    @objc func resetAction() {
        // 重置
        resultView.cleanAll()
        resultView.isHidden = true
        rightBarItem.isHidden = false
    }
    
    
    /// 翻译图片
    func translationPicture(image: UIImage) {
        
        resultView.addItem(TranslationPictureResultItem(type: 0, image: image))
        resultView.isHidden = false
        rightBarItem.isHidden = true
        
        // 图片压缩到 1M 以内
        if let newImageData = image.compress(maxSize: 1024 * 1024) {
            let lang = language == .zh ? ("zh", "ru"): ("ru", "zh")
            let target = OtherAPI.pictureOCR(image: newImageData, from: lang.0, to: lang.1, isTranslation: true)
            YLHUD.showLottie()
            YLRequest.request(target) { [self] result in
                switch result {
                case .success(let res):
                    let dataDictionary = res.dataDictionary
                    
                    let model = JsonUtil.modelFromDictionary(dataDictionary, TranslationPictureModel.self)
                    DispatchQueue.global(qos: .userInitiated).async {
                        if let resImage = model?.ocr_translate_image_base64.base64ToImage {
                            DispatchQueue.main.async { [self] in
                                YLHUD.hideHUD()
                                resultView.addItem(TranslationPictureResultItem(type: 1, image: resImage))
                            }
                        } else {
                            DispatchQueue.main.async {
                                let detail: String = (dataDictionary["detail"] as? String) ?? ""
                                xLog("图片翻译失败 \(detail)")
                                YLHUD.showMessage("图片翻译失败" + detail)
                            }
                        }
                        
                    }
                    
                case .failure(let err):
                    YLHUD.showHint(.error, err.errMsg)
                    resetAction()
                    
                }
                
            }
        }
    }
    
}

// MARK: - 拍照
extension TranslationPictureController: AVCapturePhotoCaptureDelegate {
    
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        if let imageData = photo.fileDataRepresentation() {
            // 将 Data 转换为 UIImage
            let capturedImage = UIImage(data: imageData)!
            // 处理图片，例如显示在 UIImageView 上等操作...
            translationPicture(image: capturedImage)
            
        } else {
            print("Error: Could not process captured photo.")
        }
    }
}


// MARK: - UIImagePickerControllerDelegate
extension TranslationPictureController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let originalImage = info[.originalImage] as? UIImage {
            // 使用原始图片（如果没有编辑的话）
            print("使用原始图片")
            translationPicture(image: originalImage)
        }
        dismiss(animated: true, completion: nil) // 关闭图片选择器
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil) // 用户取消选择，关闭图片选择器
    }
}


class TranslationPictureModel: BaseModel {
    var ocr_result_json: String = ""
    var ocr_result_text: String = ""
    var ocr_result_text_trans: String = ""
    var ocr_translate_image_base64: String = ""
    var original_filename: String = ""
    var saved_filename: String = ""
    var status: String = ""
}
